#include "logdialog.h"
#include <QCloseEvent>
#include <QFileDialog>
#include <QMessageBox>
#include <QApplication>
#include <QClipboard>
#include <QTextCursor>
#include <QTextStream>
#include <QStandardPaths>
#include <QDir>

LogDialog::LogDialog(QWidget *parent)
    : QDialog(parent)
    , m_logTextEdit(nullptr)
    , m_clearButton(nullptr)
    , m_saveButton(nullptr)
    , m_copyButton(nullptr)
    , m_closeButton(nullptr)
    , m_autoScrollCheckBox(nullptr)
    , m_statusLabel(nullptr)
    , m_autoScroll(true)
    , m_maxLines(1000)
{
    setupUI();
    setWindowTitle("日志查看器");
    setWindowIcon(QIcon(":/icons/log.png")); // 如果有图标的话
    resize(800, 600);
    
    // 设置窗口标志，允许最小化和最大化
    setWindowFlags(Qt::Dialog | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
}

LogDialog::~LogDialog()
{
}

void LogDialog::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 创建状态栏
    m_statusLabel = new QLabel("准备就绪");
    m_statusLabel->setStyleSheet("QLabel { color: #666; font-size: 12px; padding: 5px; }");
    mainLayout->addWidget(m_statusLabel);
    
    // 创建日志文本编辑器
    m_logTextEdit = new QTextEdit();
    m_logTextEdit->setReadOnly(true);
    m_logTextEdit->setFont(QFont("Consolas", 10)); // 使用等宽字体
    m_logTextEdit->setStyleSheet(
        "QTextEdit {"
        "    background-color: #2b2b2b;"
        "    color: #ffffff;"
        "    border: 1px solid #555;"
        "    selection-background-color: #3399ff;"
        "}"
    );
    mainLayout->addWidget(m_logTextEdit);
    
    // 创建控制按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    
    // 自动滚动复选框
    m_autoScrollCheckBox = new QCheckBox("自动滚动");
    m_autoScrollCheckBox->setChecked(m_autoScroll);
    connect(m_autoScrollCheckBox, &QCheckBox::toggled, this, &LogDialog::onAutoScrollToggled);
    buttonLayout->addWidget(m_autoScrollCheckBox);
    
    // 添加弹簧，将按钮推到右侧
    buttonLayout->addStretch();
    
    // 清空按钮
    m_clearButton = new QPushButton("清空日志");
    m_clearButton->setIcon(QIcon(":/icons/clear.png"));
    connect(m_clearButton, &QPushButton::clicked, this, &LogDialog::onClearClicked);
    buttonLayout->addWidget(m_clearButton);
    
    // 复制按钮
    m_copyButton = new QPushButton("复制全部");
    m_copyButton->setIcon(QIcon(":/icons/copy.png"));
    connect(m_copyButton, &QPushButton::clicked, this, &LogDialog::onCopyClicked);
    buttonLayout->addWidget(m_copyButton);
    
    // 保存按钮
    m_saveButton = new QPushButton("保存日志");
    m_saveButton->setIcon(QIcon(":/icons/save.png"));
    connect(m_saveButton, &QPushButton::clicked, this, &LogDialog::onSaveClicked);
    buttonLayout->addWidget(m_saveButton);
    
    // 关闭按钮
    m_closeButton = new QPushButton("关闭");
    m_closeButton->setIcon(QIcon(":/icons/close.png"));
    connect(m_closeButton, &QPushButton::clicked, this, &QDialog::close);
    buttonLayout->addWidget(m_closeButton);
    
    mainLayout->addLayout(buttonLayout);
    
    // 设置布局边距
    mainLayout->setContentsMargins(10, 10, 10, 10);
    mainLayout->setSpacing(10);
}

void LogDialog::appendLog(const QString &message)
{
    if (!m_logTextEdit) return;
    
    // 限制最大行数
    if (m_logTextEdit->document()->blockCount() > m_maxLines) {
        QTextCursor cursor = m_logTextEdit->textCursor();
        cursor.movePosition(QTextCursor::Start);
        cursor.select(QTextCursor::LineUnderCursor);
        cursor.removeSelectedText();
        cursor.deleteChar(); // 删除换行符
    }
    
    m_logTextEdit->append(message);
    
    if (m_autoScroll) {
        scrollToBottom();
    }
    
    // 更新状态
    m_statusLabel->setText(QString("日志行数: %1").arg(m_logTextEdit->document()->blockCount()));
}

void LogDialog::appendLogWithTimestamp(const QString &message)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString logMessage = QString("[%1] %2").arg(timestamp).arg(message);
    appendLog(logMessage);
}

void LogDialog::clearLog()
{
    if (m_logTextEdit) {
        m_logTextEdit->clear();
        m_statusLabel->setText("日志已清空");
    }
}

void LogDialog::saveLogToFile(const QString &filePath)
{
    if (!m_logTextEdit) return;
    
    QString fileName = filePath;
    if (fileName.isEmpty()) {
        // 默认保存位置
        QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
        defaultPath += QString("/3DModelOptimizer_Log_%1.txt")
                      .arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
        
        fileName = QFileDialog::getSaveFileName(
            this,
            "保存日志文件",
            defaultPath,
            "文本文件 (*.txt);;所有文件 (*.*)"
        );
    }
    
    if (fileName.isEmpty()) return;
    
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out.setCodec("UTF-8");
        out << m_logTextEdit->toPlainText();
        file.close();
        
        m_statusLabel->setText(QString("日志已保存到: %1").arg(fileName));
        QMessageBox::information(this, "保存成功", QString("日志已保存到:\n%1").arg(fileName));
    } else {
        QMessageBox::warning(this, "保存失败", QString("无法保存日志文件:\n%1").arg(fileName));
    }
}

void LogDialog::setAutoScroll(bool enable)
{
    m_autoScroll = enable;
    if (m_autoScrollCheckBox) {
        m_autoScrollCheckBox->setChecked(enable);
    }
}

QString LogDialog::getLogContent() const
{
    if (m_logTextEdit) {
        return m_logTextEdit->toPlainText();
    }
    return QString();
}

void LogDialog::closeEvent(QCloseEvent *event)
{
    // 隐藏窗口而不是关闭
    hide();
    event->ignore();
}

void LogDialog::onClearClicked()
{
    if (QMessageBox::question(this, "确认清空", "确定要清空所有日志内容吗？", 
                             QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        clearLog();
    }
}

void LogDialog::onSaveClicked()
{
    saveLogToFile();
}

void LogDialog::onCopyClicked()
{
    if (m_logTextEdit) {
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(m_logTextEdit->toPlainText());
        m_statusLabel->setText("日志内容已复制到剪贴板");
    }
}

void LogDialog::onAutoScrollToggled(bool enabled)
{
    m_autoScroll = enabled;
    if (enabled) {
        scrollToBottom();
    }
}

void LogDialog::scrollToBottom()
{
    if (m_logTextEdit) {
        QTextCursor cursor = m_logTextEdit->textCursor();
        cursor.movePosition(QTextCursor::End);
        m_logTextEdit->setTextCursor(cursor);
        m_logTextEdit->ensureCursorVisible();
    }
}
